package com.wlyuan.open.domain.api.service;

import com.wlyuan.core.exception.ValueError;
import com.wlyuan.open.domain.api.OpenApiInfo;
import com.wlyuan.open.domain.api.assembler.OpenApiInfoAssembler;
import com.wlyuan.open.domain.api.respository.OpenApiInfoRepository;
import com.wlyuan.open.domain.api.valueobj.OpenApiId;
import com.wlyuan.open.domain.client.respository.OpenClientRepository;
import com.wlyuan.open.vo.OpenApiCompanyDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

/**
 * @author lijing
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenApiInfoService {
    private final OpenClientRepository openClientRepository;
    private final OpenApiInfoRepository openApiInfoRepository;

    public OpenApiInfo getOpenApiInfo(String appId, Long apiId) {
        var appClient = openClientRepository.ofAppId(appId);
        if (appClient == null) {
            throw new ValueError("应用不存在");
        }
        var openApiInfo = openApiInfoRepository.getByClientIdAndApiId(appClient.getId(), new OpenApiId(apiId));
        if (openApiInfo == null) {
            throw new ValueError("该接口无权限使用");
        }
        return openApiInfo;
    }

    public void apiCall(OpenApiCompanyDetailVO dto) {
        var openApiInfo = OpenApiInfoAssembler.assemble(dto);
        openApiInfo.decreaseTotalNum();
        openApiInfo.increaseLeaveNum();
        openApiInfoRepository.save(openApiInfo);
    }
}
